﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Data;
using System.DirectoryServices;
using System.Collections;

namespace CMD.BAL.AUTH
{
    [DataContractAttribute]
    public class User
    {
        [DataMemberAttribute(EmitDefaultValue = false)]
        public int idUsr;
        [DataMemberAttribute(EmitDefaultValue = false)]
        public string mail;
        [DataMemberAttribute(EmitDefaultValue = false)]
        public string name;
        [DataMemberAttribute(EmitDefaultValue = false)]
        public List<Rol> roles;
        [DataMemberAttribute(EmitDefaultValue = false)]
        public string wUsr;
        //[DataMemberAttribute(EmitDefaultValue = false)]
        //public List<UserData> users;


        public static CMD.BAL.MISC.DeleteStateMsg Delete(int[] aIdUsr)
        {
            CMD.BAL.MISC.DeleteStateMsg delete;
            //convirto
            string join = String.Join(", ", aIdUsr);
            //ejecuto el store
            try
            {
                int dt = CMD_WEB.DAL.SrvDB.ExecuteNonQuery("exec SP_CMD_DELETEUSER'" + join + "'");
                delete = new MISC.DeleteStateMsg("registros eliminados " + dt.ToString(), true);
                return delete;
            }
            catch (Exception ex)
            {
                delete = new MISC.DeleteStateMsg("error al eliminar" + ex, false);
                return delete;
            }
        }
        public static List<User> GetData(int[] aIdUsr, bool getRolList)
        {
            string join = String.Join(", ", aIdUsr);
            DataTable dt = CMD_WEB.DAL.SrvDB.ExecuteQuery("exec SP_CMD_GETUSER'" + join + "','" + getRolList + "'");
            if (dt.Rows.Count == 0)
            {
                return null;
            }
            else
            {
                List<User> list = dt.AsEnumerable().Select(
                    row => new User
                    {
                        idUsr = row.Field<int?>(0).GetValueOrDefault(),
                        mail = String.IsNullOrEmpty(row.Field<string>(2))
                        ? ""
                        : row.Field<string>(2),
                        name = String.IsNullOrEmpty(row.Field<string>(1))
                        ? ""
                        : row.Field<string>(1),
                        wUsr = String.IsNullOrEmpty(row.Field<string>(3))
                        ? ""
                        : row.Field<string>(3),
                    }
                    ).ToList();
                return list;
            }
        }
        public static List<User> GetDataByIdRol(string[] aIsRol, bool getRolList)
        {
            string join = String.Join(", ", aIsRol);
            DataTable dt = CMD_WEB.DAL.SrvDB.ExecuteQuery("exec SP_CMD_GETUSER'" + join + "','" + getRolList + "'");
            if (dt.Rows.Count == 0)
            {
                return null;
            }
            else
            {
                List<User> list = dt.AsEnumerable().Select(
                    row => new User
                    {
                        //idRol= String.IsNullOrEmpty(row.Field<string>(0))
                        //? ""
                        //: row.Field<string>(0),
                        idUsr = row.Field<int?>(0).GetValueOrDefault(),
                        mail = String.IsNullOrEmpty(row.Field<string>(2))
                        ? ""
                        : row.Field<string>(2),
                        name = String.IsNullOrEmpty(row.Field<string>(1))
                        ? ""
                        : row.Field<string>(1),
                        wUsr = String.IsNullOrEmpty(row.Field<string>(3))
                        ? ""
                        : row.Field<string>(3),
                    }
                    ).ToList();
                return list;
            }
        }
        public static CMD.BAL.MISC.UpsertStateMsg Upsert(User usr)
        {
            CMD.BAL.MISC.UpsertStateMsg insertUser;
            try
            {
                int dt = CMD_WEB.DAL.SrvDB.ExecuteNonQuery("exec SP_CMD_UPSERTUSER'" + usr + "'");
                insertUser = new MISC.UpsertStateMsg("registros guardados " + dt.ToString(), true);
                return insertUser;

            }
            catch (Exception ex)
            {
                insertUser = new MISC.UpsertStateMsg("error al guardar " + ex, false);
                return insertUser;
            }
        }
        public User() { }
        public User(int idUsr, string mail, string name, string wUsr)
        {
            this.idUsr = idUsr;
            this.mail = mail;
            this.name = name;
            this.wUsr = wUsr;
        }

        /// <summary>
        /// BZG
        /// Obtiene un arreglo de la clase Userdata para la obtencion de los correos por grupo de Active Directory
        /// </summary>
        /// <param name="group"></param>
        /// <returns></returns>
        public List<UserData> GetListUserData(string group)
        {
            List<UserData> users = new List<UserData>();
            DirectoryEntry de = new DirectoryEntry();
            SearchResultCollection SR;
            DirectorySearcher ds = new DirectorySearcher(de, "(objectClass=person)");
            ds.Filter = "(&(objectClass=group)(cn=" + group + "))";
            try
            {
                SR = ds.FindAll();
            }
            catch (System.Runtime.InteropServices.COMException)
            {
                System.Runtime.InteropServices.COMException exception = new System.Runtime.InteropServices.COMException();
                Console.WriteLine(exception);
            }
            catch (InvalidOperationException)
            {
                InvalidOperationException InvOpEx = new InvalidOperationException();
                Console.WriteLine(InvOpEx.Message);
            }
            catch (NotSupportedException)
            {
                NotSupportedException NotSuppEx = new NotSupportedException();
                Console.WriteLine(NotSuppEx.Message);
            }
            


            foreach (SearchResult result in ds.FindAll())
            {
                var dir = result.GetDirectoryEntry();
                var list = dir.Invoke("Members");
                IEnumerable entries = (IEnumerable)list;
                foreach (var entry in entries)
                {
                    DirectoryEntry member = new DirectoryEntry(entry);
                    if (member.SchemaClassName != "group")
                    {
                        UserData adduser = new UserData(member.Properties["name"][0].ToString(), member.Properties["sAMAccountName"][0].ToString(), member.Properties["mail"][0].ToString(), group);
                        users.Add(adduser);
                        //string a = member.Properties["name"][0].ToString();
                        //string b = member.Properties["distinguishedName"][0].ToString();
                        //string c = member.Properties["sAMAccountName"][0].ToString();
                        //string d = member.Properties["mail"][0].ToString();
                    }
                }
            }


            return users;
        }
        public CMD.BAL.MISC.UpsertStateMsg UpsertMailbyGroup(string group, string mail)
        {

            CMD.BAL.MISC.UpsertStateMsg insertMail;
            try
            {
                int dt = CMD_WEB.DAL.SrvDB.ExecuteNonQuery("exec SP_CMD_UPSERT_SECGROUP '" + group + "','" + mail + "'");
                insertMail = new MISC.UpsertStateMsg("registros guardados " + dt.ToString(), true);
                return insertMail;
            }
            catch (Exception ex)
            {
                insertMail = new MISC.UpsertStateMsg("error al guardar " + ex, false);
                return insertMail;
            }
        }
        public string GetMailbygroup(string group)
        {
            try
            {

                DataTable dt = CMD_WEB.DAL.SrvDB.ExecuteQuery("exec x '" + group + "'");
                if (dt.Rows.Count == 0)
                    return "";
                else
                    return dt.Rows[0].ToString();
            }
            catch { return " "; }

        }
    }

    /// <summary>
    /// BZG
    /// Clase datos de usuario Active Directory
    /// </summary>
    public class UserData
    {
        public string UserName { get; set; }
        public string AccountName { get; set; }
        public string UserMail { get; set; }
        public string Group { get; set; }


        public UserData(string username, string accountname, string usermail, string group)
        {
            this.UserName = username;
            this.AccountName = accountname;
            this.UserMail = usermail;
            this.Group = group;
        }
    }
}
